package cn.dai.SocketProgramming;

import org.junit.Test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author ArkD42
 * @file 1 - Java基础语法
 * @create 2020 - 04 - 22 - 20:11
 */
public class UDP_Test {

    @Test
    public void send() throws Exception {

        DatagramSocket ds = new DatagramSocket();

        java.lang.String message = "来自发送器的消息：Hello UDP!!!";
        byte[] bytes = message.getBytes();
        InetAddress localHost = InetAddress.getLocalHost();
        DatagramPacket dp = new DatagramPacket(bytes,0,bytes.length,localHost,65000);

        // 发送包
        ds.send(dp);

        ds.close();
    }

    @Test
    public void receive() throws Exception{
        DatagramSocket ds = new DatagramSocket(65000);

        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
        ds.receive(packet);

        System.out.println(new String(packet.getData(),0,packet.getLength()));

        ds.close();
    }

}
